#include "spi.h"
#include "esp_log.h"

static const char *TAG = "SPI_TEST";

// 初始化 SPI 主机
esp_err_t spi_master_init(void)
{
    ESP_LOGI(TAG, "Initializing SPI master...");

    spi_bus_config_t buscfg = {0};
    
    buscfg.miso_io_num = SPI_MASTER_MISO_IO;
    buscfg.mosi_io_num = SPI_MASTER_MOSI_IO;
    buscfg.sclk_io_num = SPI_MASTER_SCLK_IO;
    buscfg.quadwp_io_num = -1;
    buscfg.quadhd_io_num = -1;

    esp_err_t ret = spi_bus_initialize(SPI_MASTER_NUM, &buscfg, SPI_DMA_CH_AUTO);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "SPI bus initialization failed: %s", esp_err_to_name(ret));
        return ret;
    }

    spi_device_interface_config_t devcfg = {0};
    
    devcfg.clock_speed_hz = 1000000;
    devcfg.mode = 0;
    devcfg.spics_io_num = SPI_MASTER_CS_IO;
    devcfg.queue_size = 7;
    devcfg.pre_cb = NULL;

    ret = spi_bus_add_device(SPI_MASTER_NUM, &devcfg, NULL);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "SPI device addition failed: %s", esp_err_to_name(ret));
    }

    return ret;
}

// 向 SPI 从机写入数据
esp_err_t spi_master_write(uint8_t *data, size_t size)
{
    spi_transaction_t t = {
        .length = size * 8,
        .tx_buffer = data,
        .rx_buffer = NULL,
    };
    esp_err_t ret = spi_device_transmit(NULL, &t);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "SPI write failed: %s", esp_err_to_name(ret));
    }
    return ret;
}

// 从 SPI 从机读取数据
esp_err_t spi_master_read(uint8_t *data, size_t size)
{
    spi_transaction_t t = {
        .length = size * 8,
        .tx_buffer = NULL,
        .rx_buffer = data,
    };
    esp_err_t ret = spi_device_transmit(NULL, &t);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "SPI read failed: %s", esp_err_to_name(ret));
    }
    return ret;
}
